const PROMISE_STATUS_PENDING = "pending";
const PROMISE_STATUS_FULFILLED = "fulfilled";
const PROMISE_STATUS_REJECT = "rejected";

class HSPromise {
    constructor(executor) {
        this.status = PROMISE_STATUS_PENDING;
        this.value = undefined
        this.reason = undefined
        this.onFulfilledFns = []
        this.onRejectedFns = []

        const resolve = (value) => {
            if (this.status === PROMISE_STATUS_PENDING) {
                queueMicrotask(() => {
                if (this.status !== PROMISE_STATUS_PENDING) return
                    this.status = PROMISE_STATUS_FULFILLED;
                    this.value = value
                    console.log("resolve被调用");
                    // then 传进来的第一个回调函数
                    // this.onFulfilled(this.value)
                    this.onFulfilledFns.forEach(fn => {
                        fn(this.value)
                    })
                })
            }
        };
        const reject = (reason) => {
            if (this.status === PROMISE_STATUS_PENDING) {
                queueMicrotask(() => {
                if (this.status !== PROMISE_STATUS_PENDING) return
                    this.status = PROMISE_STATUS_REJECT;
                    this.reason = reason
                    console.log("reject被调用");
                    // then 传进来的第二个回调函数
                    // this.onRejected(this.reason)
                    this.onRejectedFns.forEach(fn => {
                        fn(this.reason)
                    })
                })

            }
        };
        executor(resolve, reject);
    }

    then(onFulfilled, onRejected) {
        if (this.status === PROMISE_STATUS_FULFILLED && onFulfilled) {
            onFulfilled(this.value)
        }
        if (this.status === PROMISE_STATUS_REJECT && onRejected) {
            onRejected(this.reason)
        }

        //将成功回调和失败的回调放到数组中
        this.onFulfilledFns.push(onFulfilled)
        this.onRejectedFns.push(onRejected)
    }
}

const promise = new HSPromise((resolve, reject) => {
    console.log("状态pending");
    resolve(11112222);
    reject(22222);
});

promise.then(res => {
        console.log("res1", res)
    },
    err => {
        console.log("err1:", err)
    })

promise.then(res => {
        console.log("res2", res)
    },
    err => {
        console.log("err2:", err)
    })

//在確定Promise状态之后，再次调用then
setTimeout(() => {
    promise.then(res => {
        console.log("res3", res)
    })
}, 1000)